const fs = require('fs');
const {
    endianness
} = require('os');
const path = require('path');

function loadCSVFile(dir, fileList = []) {
    const files = fs.readdirSync(dir);
    files.forEach((item, index) => {
        var fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            loadCSVFile(path.join(dir, item), fileList); //递归读取文件
        } else {
            var extname = path.extname(fullPath)
            if (extname == ".csv") {
                fileList.push(fullPath);
            }
        }
    });
    return fileList;
}

var fileList = [];
loadCSVFile("public/build", fileList);
var str = "";
var _scs = [];
for (let index = 0; index < fileList.length; index++) {
    const element = fileList[index];
    var fileName = path.basename(element);
    // var _tmp1 = [];
    // var _tmp2 = [];
    // var file = fs.readFileSync(element, 'utf-8');
    // var arr = file.split(/[\n]/);
    // for (let _index = 0; _index < arr.length - 1; _index++) {
    //     const item = arr[_index];
    //     var _arrr = item.split(',');
    //     if (index == 0) {
    //         _tmp1.push(_arrr[0]);
    //     }
    //     if (_index == 0) {
    //         _tmp2.push("压缩" + "（" + fileName.replace(".csv", "") + "）");
    //     } else {
    //         _tmp2.push(_arrr[1]);
    //     }
    // }
    // if (index == 0) {
    //     _scs.push(_tmp1);
    // }
    // _scs.push(_tmp2);
    var _str1 = "";
    if (index == 0) {
        _str1 = "源文件,";
    }
    var _str2 = "压缩" + "（" + fileName.replace(".csv", "") + "）" + ",";
    //创建文件流
    var file = fs.readFileSync(element, 'utf-8');
    var arr = file.split(/[\n]/);
    for (let _index = 1; _index < arr.length - 1; _index++) {
        const item = arr[_index];
        var _arrr = item.split(',');
        var _end = _index == arr.length - 2 ? "" : ",";
        _str2 += _arrr[1] + _end;
        if (index == 0) {
            _str1 += _arrr[0] + _end;
        }
    }
    if (index == 0) {
        _str1 += "\n";
    }
    _str2 += "\n";
    str += _str1 + _str2;
}
// for (let index = 0; index < _scs[0].length; index++) {
//     var _tmp = "";
//     for (let _ii = 0; _ii < _scs.length; _ii++) {
//         const _item = _scs[_ii][index];
//         var _end = _ii == _scs.length - 1 ? "\n" : ",";
//         _tmp += _item + _end;
//     }
//     str += _tmp;
// }
fs.writeFileSync("public/" + 'csv.csv', str, (err) => {
    console.log('写入文件', err);
});